package com.qsl.juc.block_queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockQueueDemo {

    public static void main(String[] args) throws Exception {

        BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>(3);

        BlockingQueue<String> blockingQueue1 = new ArrayBlockingQueue<>(3);

        // add(E) 和 remove() 对应，失败操作会抛出异常
        // add(E) 里面调用的 offer(E)， offer(E) 中用到 ReentrantLock putLock 加锁
        /*blockingQueue.add("a");
        blockingQueue.add("b");
        blockingQueue.add("c");*/
        // blockingQueue.add("d");
        // remove() 里面调用的 poll()，poll 中用到 ReentrantLock takeLock 加锁
        /*blockingQueue.remove();
        blockingQueue.remove();
        blockingQueue.remove();*/
        // blockingQueue.remove();

        // offer(E) 和 poll() 对应，offer 失败返回 false，poll 失败返回 null
        // offer 中用到 ReentrantLock putLock，poll 中用到  ReentrantLock takeLock
        /*blockingQueue.offer("a");
        blockingQueue.offer("b");
        blockingQueue.offer("c");
        System.out.println(blockingQueue.offer("d"));
        blockingQueue.poll();
        blockingQueue.poll();
        blockingQueue.poll();
        System.out.println(blockingQueue.poll());*/

        // pu(E) 和 take() 对应， 失败后会挂起阻塞
        // put 无返回值，take 返回出队的元素
        /*blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        //blockingQueue.put("d");
        blockingQueue.take();
        blockingQueue.take();
        blockingQueue.take();
        // blockingQueue.take();*/

        // offer(E e, long timeout, TimeUnit unit) 与 poll(long timeout, TimeUnit unit) 对应
        // ConditionObject 的 long awaitNanos(long nanosTimeout)， 1000 ns 用自旋，而不依赖 LockSupport
        blockingQueue.offer("a", 3, TimeUnit.SECONDS);
        blockingQueue.offer("b", 3, TimeUnit.SECONDS);
        System.out.println(blockingQueue.offer("c", 3, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("d", 3, TimeUnit.SECONDS));
        System.out.println("==========");
        blockingQueue.poll(3, TimeUnit.SECONDS);
        blockingQueue.poll(3, TimeUnit.SECONDS);
        System.out.println(blockingQueue.poll(3, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(3, TimeUnit.SECONDS));
    }

}
